﻿using System.Collections;
using Unity.Burst;
using Unity.Entities;
using Unity.Entities.Content;
using Unity.Mathematics;
using Unity.Scenes;
using UnityEngine;
using static UnityEngine.EventSystems.EventTrigger;

public struct PrefabInSceneSpawner : IComponentData
{
    public Entity entity;
}

public class TestPrefabInScene : MonoBehaviour
{
    public GameObject prefab;

    public class Baker : Baker<TestPrefabInScene>
    {
        public override void Bake(TestPrefabInScene authoring)
        {
            Entity spawnerEntity = GetEntity(TransformUsageFlags.None);

            AddComponent(spawnerEntity, new PrefabInSceneSpawner()
            {
                entity = GetEntity(authoring.prefab, TransformUsageFlags.Dynamic)
            }); ;
        }
    }
}

[BurstCompile]
[RequireMatchingQueriesForUpdate]
public partial struct TestPrefabInSceneSystem : ISystem
{
    private int frame;

    [BurstCompile]
    void OnCreate(ref SystemState state)
    {
        frame = 0;
    }

    [BurstCompile]
    public partial struct LoadJob : IJobEntity
    {
        public EntityCommandBuffer ecb;
        public Unity.Mathematics.Random random;

        // 加载回调
        void Execute(Entity entity, in PrefabInSceneSpawner spawner)
        {
            Entity inst = ecb.Instantiate(spawner.entity);

            ecb.SetComponent(inst, new Unity.Transforms.LocalTransform()
            {
                Position = random.NextFloat3(new float3(-3.0f, -3.0f, -3.0f), new float3(3.0f, 3.0f, 3.0f)),
                Rotation = quaternion.identity,
                Scale = 1.0f
            });

            Debug.Log("GGGGGGGGGGGGGGGGGGG");
        }
    }

    [BurstCompile]
    void OnUpdate(ref SystemState state)
    {
        frame++;

        // 每隔300帧加载一个球
        if ((frame + 30) % 300 != 0)
        {
            return;
        }

        var ecbSingleton = SystemAPI.GetSingleton<EndSimulationEntityCommandBufferSystem.Singleton>();
        EntityCommandBuffer ecb = ecbSingleton.CreateCommandBuffer(state.WorldUnmanaged);

        Unity.Mathematics.Random random = new Unity.Mathematics.Random((uint)SystemAPI.Time.ElapsedTime * 1000);

        // 加载回调Job
        LoadJob job = new LoadJob
        {
            ecb = ecb,
            random = random,
        };
        job.Schedule();

        Debug.Log("FFFFFFFFFFFFFFFFFFFF");
    }
}